package com.cskaoyan.order.mq;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderRequest;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderResponse;
import com.cskaoyan.order.service.OrderPromoService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author 牟治宇
 * @description 
 * @date 2022/8/8 14:14
 * @param 
 * @return 
 */
@Component
public class PromoOrderConsumer {
    DefaultMQPushConsumer consumer;

    @Autowired
    OrderPromoService orderPromoService;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("promo_order_consumer");

        consumer.setNamesrvAddr("127.0.0.1:9876");

        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                // 获取消息中的数据
                MessageExt message = msgs.get(0);
                byte[] body = message.getBody();
                CreateSeckillOrderResponse promoOrder = null;
                String s = new String(body, 0, body.length, StandardCharsets.UTF_8);

                CreateSeckillOrderRequest createSeckillOrderRequest = JSON.parseObject(s, CreateSeckillOrderRequest.class);

                promoOrder = orderPromoService.createPromoOrder(createSeckillOrderRequest);

                // 根据response的结果，返回消息消费的结果
                if (OrderRetCode.SUCCESS.getCode().equals(promoOrder.getCode())){
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });

        try {
            consumer.subscribe("promo_order", "*");
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
